# 1.从文件中读取数据
with open('file.txt') as f:
    content = f.read()
    print(content.rstrip())


# 2.逐行读取
with open('file.txt') as f:
    for i in f:
        print(i.rstrip()) # 去掉末尾的换行

# 3.写入文件
filename = 'programming.txt'
# 'w'会覆盖掉原本的文件内容，如果不想覆盖掉原本的文件内容，可以指定 'a' 选项
with open(filename, 'w') as f:
    f.write("This is a test1!\n")
    f.write("This is a test2!\n")


# 4. try-except 代码块
try:
    print(5 / 0)
except ZeroDivisionError:
    print("Division by zero")


# 5.存储数据 使用 json.dump()和 json.load()
import json
numbers = [1, 2, 3, 4, 5]
# 写入文件
filename = 'number.txt'
with open(filename, 'w') as f:
    json.dump(numbers, f)
# 读取文件
with open('number.txt') as f:
    number = json.load(f)
print(number)